package com.jt.proxy;

import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {
    //传入target目标对象获取代理对象
    //利用代理对象 实现方法的拓展
    public static Object getProxy(Object target){
        //1.获取类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        //2.获取接口的数组类型
        Class<?>[] interfaces = target.getClass().getInterfaces();
        //3.代理对象执行方法时的回调方法(代理对象调用方法时，执行InvocationHandler)
        return Proxy.newProxyInstance(classLoader,interfaces,invocationHandler(target));
    }

    //必须传递目标对象
    public static InvocationHandler invocationHandler(Object target){
        return new InvocationHandler() {
            /**
             * 参数说明
             *      1.proxy代理对象
             *      2.method当前执行的方法对象
             *      3.方法的参数
             * @param proxy
             * @param method
             * @param args
             * @return
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("事务开始");
                //获取目标方法的返回值
                Object result = method.invoke(target, args);
                System.out.println("事务提交");
                return result;
            }
        };
//        return new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                System.out.println("开启事务");
//                Object result = method.invoke(target, args);
//                System.out.println("关闭事务");
//                return result;
//            }
//        };
    }

    public static Object getProxy1(Object target){
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        return Proxy.newProxyInstance(classLoader,interfaces ,invocationHandler1(target) );
    }

    public static InvocationHandler invocationHandler1(Object target){
        return new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                long t1 =System.currentTimeMillis();
                Object result = method.invoke(target,args);
                long t2 = System.currentTimeMillis();
                long time = t2-t1;
                System.out.println("耗时:"+time);
                return result;
            }
        };
    }
}
